package com.mfp.java.testYou.db.model;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import com.mfp.java.testYou.core.AppContext;

/**
 * Not DB class
 * 
 */
public class TestManager {

	private TestManager() {
	}

	public static TakenTest createTest(Integer testId) {
		TakenTest tt = new TakenTest();
		tt.setTestId(testId);

		Test test = AppContext.getDAO().getTest(testId);
		List<Question> testQuestions = test.getQuestions();
		Collections.shuffle(testQuestions);

		List<AnsweredQuestion> ansQuestions = new LinkedList<AnsweredQuestion>();
		List<Integer> questIds = new LinkedList<Integer>();

		for (Question q : testQuestions) {
			AnsweredQuestion aq = new AnsweredQuestion(q.getId());
			ansQuestions.add(aq);
			questIds.add(q.getId());
		}

		tt.setAnswers(ansQuestions);
		tt.setQuestionIds(questIds);
		tt.setAllowHints(test.isAllowHints());
		return tt;
	}

	public static void setAnswer(TakenTest tt, Integer questionNo, List<Integer> trueAnswers) {
		AnsweredQuestion aq = tt.getAnswers().get(questionNo);
		Integer qId = tt.getQuestionIds().get(questionNo);
		Question question = AppContext.getDAO().getQuestion(qId);
		List<Answer> answers = question.getAnswers();

		Boolean[] corr = new Boolean[answers.size()];

		for (int i = 0; i < answers.size(); i++) {
			if (trueAnswers.contains(answers.get(i).getId())) {
				corr[i] = true;
			} else {
				corr[i] = false;
			}
		}
		aq.setGivenAnswers(corr);
	}

	public static void finishTest(TakenTest tt) {
		List<AnsweredQuestion> aqList = tt.getAnswers();

		float totalCount = 0;
		float correctCount = 0;

		for (AnsweredQuestion aq : aqList) {
			Integer qId = aq.getQuestionId();
			Question q = AppContext.getDAO().getQuestion(qId);

			Boolean[] corr = new Boolean[q.getAnswers().size()];

			int i = 0;
			for (Answer a : q.getAnswers()) {
				if (a.isCorect()) {
					corr[i] = true;
				} else {
					corr[i] = false;
				}
				i++;
			}

			boolean correct = true;
			for (int j = 0; j < aq.getGivenAnswers().length; j++) {
				if (corr[j] != aq.getGivenAnswers()[j]) {
					correct = false;
					break;
				}
			}
			aq.setCorrect(correct);

			totalCount++;
			if (aq.isCorrect()) {
				correctCount++;
			}
		}

		tt.setResult(correctCount / totalCount);
	}
}
